import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {Headers, RequestOptions} from "@angular/http";
import {ModalDirective} from "ngx-bootstrap";
import {AddInvitation} from "../../invitation/list/list.component";
import {tuikeSystemUrl, adSystemApiUrl, AliyunOssOutputUrl} from "../../../../config/api";
import {HttpService} from "../../../lib/service/http.service";
import {AdOssUploadService} from "../../../lib/service/ad-oss-upload.service";
import * as moment from 'moment';
import {ActivatedRoute, Router} from "@angular/router";
import {LoginService} from "../../../lib/service/tuike-login.service";

export class AddRobot {
  nickName: string;
  member_store_name: string;
  avatar_url: string;
}

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
  addInvitation = new AddInvitation;
  addRobot = new AddRobot;
  searchData = '';
  status = '';
  tuikeSystemUrl = tuikeSystemUrl;
  adSystemApiUrl = adSystemApiUrl;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  type: string;
  message: string;
  isShow = true;
  totalItems: number;
  currentPage: number = 1;
  itemsPerPage: number = 20;
  _isSpinning = false;
  error = false;
  addStatus = false;
  selectStatus = '1';
  robotList = [];
  IntegralList = [];
  editRobotId = '';
  editIntegralId = '';
  picError = false;
  fileList = [];
  picList = [];
  picSizeInfo = '只可上传一次';
  integral = 0;
  _date = null;
  IntegralError = false;
  canChange = false;
  canVisit = false;
  canVisit1 = false;
  canVisit2 = false;
  canVisit3 = false;


  @ViewChild('resetPsdModal') public resetPsdModal: ModalDirective;
  @ViewChild('addModal') public addModal: ModalDirective;
  @ViewChild('confirmModal') public confirmModal: ModalDirective;
  @ViewChild('addIntegralModal') public addIntegralModal: ModalDirective;


  constructor(
    private httpService: HttpService,
    private element: ElementRef,
    private adOssUploadService: AdOssUploadService,
    private route: ActivatedRoute,
    private router: Router,
    private loginService: LoginService
  ) {
  }

  ngOnInit() {
    let type = null;
    this.canVisit = this.loginService.canVisitCheck('add_robot');
    this.canVisit1 = this.loginService.canVisitCheck('delete_robot');
    this.canVisit2 = this.loginService.canVisitCheck('add_integral');
    this.canVisit3 = this.loginService.canVisitCheck('delete_integral');

    this.router.url == '/tuike/robot/list' ? type = 1 : type = 2;
    if(type == 1) {
      this.selectStatus = '1';
    } else {
      this.selectStatus = '2';
    }
    this.getList();

    this._date = new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 00:00:00');
  }

  //重置
  reset() {
    this.searchData = '';
  }

  //搜索
  search() {

  }

  showAddModal() {
    this.addModal.show();
  }

  showAddIntergral(id) {
    this.addIntegralModal.show();
    this.editRobotId = id;
  }

  cancelIntegral() {
    this.addIntegralModal.hide();
    this.integral = 0;
  }

  addRobotIntegral() {
    const url = `${tuikeSystemUrl}/api/v1/admin/Member/add_robot_point`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({
      'point': this.integral,
      'member_id': this.editRobotId,
      'date': moment(this._date).format('YYYY-MM-DD HH:mm:ss')
    });
    this.httpService.httpPostAuth(url, body, options).subscribe(res => {
      if (res.code === 200) {
        this.message = '增加积分成功';
        this.isShow = true;
        this.type = 'success';
        this.addIntegralModal.hide();
        this.integral = 0;
        this._date = null;
        this.selectStatus = '2';
        this.getList();
      } else {
        this.message = res.message;
        this.isShow = true;
        this.type = 'error';
      }
    })
  }

  checkIntegral() {
    if (!/^\+?[1-9][0-9]*$/.test(this.integral + '')) {
      this.IntegralError = true;
    } else {
      this.IntegralError = false;
    }
  }

  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
      this.uploadImg();
    }
  }

  uploadImg() {
    this.fileList.every((val, idx, array) => {
      if (val && val != "pic") {
        console.log(val);
        this.adOssUploadService.getSignature2(`/api/v1/common/upload`, '/v1/admin/Member/add_robot_member', val, '')
          .subscribe(res => {
              if (res.code === 200) {
                this.message = '上传成功';
                this.isShow = true;
                this.type = 'success';
                this.addRobot.avatar_url = `${this.aliyunOssOutputUrl}${res.data[0]}`;
              }
            }
          );
      }
      return true;
    });
  }


  cancel() {
    this.addModal.hide();
    this.addRobot.member_store_name = '';
    this.addRobot.nickName = '';
    this.addRobot.avatar_url = '';
  }

  getList() {
    this.currentPage = 1;
    if(this.selectStatus == '1') {
      this.router.navigate(['tuike/robot/list']);
      this.getRobotList(1);
    } else {
      this.router.navigate(['tuike/robot/list1']);
      this.getRobotIntegralList(1);
    }
    // this.selectStatus == '1' ? this.getRobotList(1) : this.getRobotIntegralList(1);
  }


  //获取机器人列表
  getRobotList(page: number) {
    this._isSpinning = true;
    this.currentPage = 1;
    let url = `${tuikeSystemUrl}/api/v1/admin/Member/robot_member_list?page=${page}&pageSize=${this.itemsPerPage}`;
    this.httpService.httpGetAuth(url).subscribe(res => {
      this.robotList = res.data;
      this._isSpinning = false;
    })
  }

  //获取机器人积分列表
  getRobotIntegralList(page: number) {
    this._isSpinning = true;
    this.currentPage = 1;
    let url = `${tuikeSystemUrl}/api/v1/admin/Member/robot_point_list?page=${page}&pageSize=${this.itemsPerPage}`;
    this.httpService.httpGetAuth(url).subscribe(res => {
      this._isSpinning = false;
      this.IntegralList = res.data.data;
      this.totalItems = res.data.total;
    })
  }


  editRobot(id) {
    this.editRobotId = id;
  }

  showConfirmModal(id) {
    console.log(id);
    this.selectStatus == '1' ? this.editRobotId = id : this.editIntegralId = id;
    this.confirmModal.show();
  }

  //添加机器人
  addRobot1() {
    const url = `${tuikeSystemUrl}/api/v1/admin/Member/add_robot_member`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    this.httpService.httpPostAuth(url, this.addRobot, options).subscribe(res => {
      if (res.code === 200) {
        this.message = '添加成功';
        this.type = 'success';
        this.isShow = true;
        this.addModal.hide();
        this.addRobot.nickName = '';
        this.addRobot.avatar_url = '';
        this.addRobot.member_store_name = '';
        this.fileList = [];
        this.picList = [];
        this.currentPage = 1;
        this.getRobotList(1);
      } else {
        this.message = res.message;
        this.type = 'error';
        this.isShow = true;
      }
    })
  }

  //删除单条机器人积分
  deleteIntegral() {
    const url = `${tuikeSystemUrl}/api/v1/admin/Member/del_robot_point`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({'id': this.editIntegralId});
    this.httpService.httpPostAuth(url, body, options).subscribe(res => {
      if (res.code === 200) {
        this.message = '删除成功';
        this.type = 'success';
        this.isShow = true;
        this.confirmModal.hide();
        this.currentPage = 1;
        this.getRobotIntegralList(1);
      } else {
        this.message = res.message;
        this.type = 'error';
        this.isShow = true;
      }
    })
  }

  //删除机器人
  deleteRobot() {
    const url = `${tuikeSystemUrl}/api/v1/admin/Member/del_robot`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({'id': this.editRobotId});
    this.httpService.httpPostAuth(url, body, options).subscribe(res => {
      if (res.code === 200) {
        this.message = '删除成功';
        this.type = 'success';
        this.isShow = true;
        this.confirmModal.hide();
        this.currentPage = 1;
        this.getRobotList(1);
      } else {
        this.message = res.message;
        this.type = 'error';
        this.isShow = true;
      }
    })
  }

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.selectStatus == '1' ? this.getRobotList(event.page) : this.getRobotIntegralList(event.page);
  }
}

